package com.nageoffer.shortlink.admin.toolkit;

import java.security.SecureRandom;
import java.util.Random;

public final class RandomCodeUtil {
    // 定义允许的字符集：数字+小写字母+大写字母（排除易混淆字符）
    private static final String CHARACTERS = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz";
    private static final int DEFAULT_LENGTH = 6;
    private static final Random RANDOM = new SecureRandom();

    /**
     * 生成默认长度(6位)的随机字符串
     */
    public static String generate() {
        return generate(DEFAULT_LENGTH);
    }

    /**
     * 生成指定长度的随机字符串
     *
     * @param length 需要生成的字符串长度
     * @return 包含数字和字母的随机字符串
     */
    public static String generate(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("长度必须为正整数");
        }

        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            // 从字符集中随机选取一个字符
            int index = RANDOM.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }
        return sb.toString();
    }

}
